package com.rich.area.service.impl;

import com.rich.area.mapper.TbAddressMapper;
import com.rich.area.service.AddressService;
import com.rich.common.entity.TbAddress;
import io.prometheus.client.Collector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Package: com.rich.area.service.impl
 * @Author: 张dy
 * @Date: Created in 2021/8/13 下午 7:36
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private TbAddressMapper addressMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<TbAddress> findById(Long pid) {
        return addressMapper.findById(pid);
    }

    @Override
    public List<Map> findTree() {

        List<Map> treeAddress =
                (List<Map>) redisTemplate.boundListOps("treeAddress").rightPop();
        if (treeAddress != null) {
            return treeAddress;
        }
        List<Map> maps = new ArrayList<>();
        List<TbAddress> byId = addressMapper.findAll();

        for (TbAddress tbAddress : byId) {
            if (tbAddress.getParentId().longValue()==0){
                Map<Object, Object> map = new HashMap<>(64);
                map.put("id", tbAddress.getId());
                map.put("name", tbAddress.getName());
                map.put("parentId", tbAddress.getParentId());
                List<Map> list = findTreeById(tbAddress, byId);
                if (list!=null) {
                    map.put("addressVo", list);
                }
                maps.add(map);
            }
        }
        redisTemplate.boundListOps("treeAddress").rightPush(maps);
        return maps;


    }

    private List<Map> findTreeById(TbAddress address, List<TbAddress> all) {
        List<Map> maps = new ArrayList<>();
        for (TbAddress tbAddress : all) {
            if (tbAddress.getParentId().longValue()==address.getId().longValue()){
                Map<Object, Object> map = new HashMap<>(64);
                map.put("id", tbAddress.getId());
                map.put("name", tbAddress.getName());
                map.put("parentId", tbAddress.getParentId());
                List<TbAddress> byId = findById(tbAddress.getId());
                List<Map> list = findTreeById(tbAddress, byId);
                if (list!=null) {
                    map.put("addressVo", list);
                }
                maps.add(map);
            }
        }
        return maps;
    }


}
